package com.cmf.myproject.service.system.user;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cmf.myproject.dal.mybatis.mapper.BossUserMapper;
import com.cmf.myproject.dal.mybatis.mapper.UserMapper;
import com.cmf.myproject.dal.mybatis.model.BossUser;
import com.cmf.myproject.dal.mybatis.model.BossUserExample;
import com.cmf.myproject.dal.mybatis.model.BossUserExample.Criteria;
import com.cmf.myproject.dal.mybatis.model.User;
import com.cmf.myproject.dal.mybatis.model.UserExample;
import com.cmf.myproject.dal.mybatis.mymapper.MyBossUserMapper;
import com.cmf.myproject.dal.mybatis.mymodel.BossUserRole;
import com.cmf.myproject.service.system.user.dto.BossUserAddItemReqDto;
import com.cmf.myproject.service.system.user.dto.BossUserQueryFilter;
import com.cmf.myproject.service.system.user.dto.BossUserUpdateItemReqDto;
import com.cmf.myproject.service.system.user.dto.UserChangePasswdReqDto;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.system.core.results.ResultBase;
import com.system.core.view.layui.table.TableViewRspDto;

@Service
public class BossUserService {
	
private SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Autowired
	private BossUserMapper bossUserMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private MyBossUserMapper myBossUserMapper;
	
	@Transactional
	public ResultBase changePasswd(UserChangePasswdReqDto userChangePasswdReqDto) {
		ResultBase resultBase = new ResultBase();
		BossUserExample bossUserExample = new BossUserExample();
		bossUserExample.createCriteria().andIdEqualTo(userChangePasswdReqDto.getUserId());
		List<BossUser> users = bossUserMapper.selectByExample(bossUserExample);
		if(users.size() != 1) {
			resultBase.setMessage("未找到用户");
			return resultBase;
		}
		BossUser user = users.get(0);
		if(!user.getPassword().equals(DigestUtils.sha256Hex(userChangePasswdReqDto.getOrigPasswd()))) {
			resultBase.setMessage("原密码错");
			return resultBase;
		}
		user.setPassword(DigestUtils.sha256Hex(userChangePasswdReqDto.getNewPasswd()));
		bossUserMapper.updateByPrimaryKeySelective(user);
		resultBase.setMessage("密码更新成功");
		resultBase.setSuccess(true);
		return resultBase;
	}
	
	@Transactional
	public ResultBase changeUserPasswd(UserChangePasswdReqDto userChangePasswdReqDto) {
		ResultBase resultBase = new ResultBase();
		UserExample userExample = new UserExample();
		userExample.createCriteria().andIdEqualTo(userChangePasswdReqDto.getUserId());
		List<User> users = userMapper.selectByExample(userExample);
		if(users.size() != 1) {
			resultBase.setMessage("未找到用户");
			return resultBase;
		}
		User user = users.get(0);
		if(!user.getPassword().equals(DigestUtils.sha256Hex(userChangePasswdReqDto.getOrigPasswd()))) {
			resultBase.setMessage("原密码错");
			return resultBase;
		}
		user.setPassword(DigestUtils.sha256Hex(userChangePasswdReqDto.getNewPasswd()));
		userMapper.updateByPrimaryKeySelective(user);
		resultBase.setMessage("密码更新成功");
		resultBase.setSuccess(true);
		return resultBase;
	}
	
	/**
	 * 页面列表查询
	 * @return TableViewRspDto 返回TableViewRspDto视图对象，符合Layui规范
	 */
	public TableViewRspDto<BossUserRole> bossUserList(BossUserQueryFilter filter){
		TableViewRspDto<BossUserRole> pageResult = new TableViewRspDto<BossUserRole>();
		BossUserExample example = new BossUserExample();
		Criteria criteria = example.createCriteria();
		//在此插入查询条件start
		/**
		 * jdbcType:timestamp
		 */
		try {
			if(StringUtils.isNotBlank(filter.getCreateTimeStrStart())) {
				criteria.andCreateTimeGreaterThanOrEqualTo(timeformat.parse(filter.getCreateTimeStrStart()));
			}
			if(StringUtils.isNotBlank(filter.getCreateTimeStrEnd())) {
				criteria.andCreateTimeLessThanOrEqualTo(timeformat.parse(filter.getCreateTimeStrEnd()));
			}
		} catch (ParseException e) {
			e.printStackTrace();
			pageResult.setMessage(e.getMessage());
			return pageResult;
		}
		if(filter.getId() != null) {
			criteria.andIdEqualTo(filter.getId());
		}
		if(filter.getIsLocked() != null) {
			criteria.andIsLockedEqualTo(filter.getIsLocked());
		}
		if(StringUtils.isNotBlank(filter.getNick())) {
			criteria.andNickEqualTo(filter.getNick());
		}
		if(StringUtils.isNotBlank(filter.getPassword())) {
			criteria.andPasswordEqualTo(filter.getPassword());
		}
		if(StringUtils.isNotBlank(filter.getPhone())) {
			criteria.andPhoneEqualTo(filter.getPhone());
		}
		/**
		 * jdbcType:timestamp
		 */
		try {
			if(StringUtils.isNotBlank(filter.getUpdateTimeStrStart())) {
				criteria.andUpdateTimeGreaterThanOrEqualTo(timeformat.parse(filter.getUpdateTimeStrStart()));
			}
			if(StringUtils.isNotBlank(filter.getUpdateTimeStrEnd())) {
				criteria.andUpdateTimeLessThanOrEqualTo(timeformat.parse(filter.getUpdateTimeStrEnd()));
			}
		} catch (ParseException e) {
			e.printStackTrace();
			pageResult.setMessage(e.getMessage());
			return pageResult;
		}
		if(StringUtils.isNotBlank(filter.getUserName())) {
			criteria.andUserNameEqualTo(filter.getUserName());
		}
		if(filter.getUserRoleId() != null) {
			criteria.andUserRoleIdEqualTo(filter.getUserRoleId());
		}
		//在此插入查询条件end
		
		Page<BossUserRole> page = PageHelper.startPage(filter.getPage(), filter.getLimit());
		example.setOrderByClause("create_time desc");
		pageResult.setData(myBossUserMapper.selectByExample(example));
		pageResult.setCount(page.getTotal());
//		pageResult.setPageSize(page.getPageSize());
		pageResult.setCode(0);
		pageResult.setMessage("查询成功");
		return pageResult;
	}
	
	/**
	 * 根据主键获取单条数据
	 * @param bossUser 使用bossUser对象的主键属性Id类型是Long
	 */
	public BossUser bossUserGetByPrimaryKey(BossUser bossUser) {
		BossUser result = bossUserMapper.selectByPrimaryKey(bossUser.getId());
		return result;
	}
	
	/**
	 * 根据主键更新数据
	 * @param bossUser 被更新对象（请注意，只更新有值属性）
	 */
	public ResultBase bossUserUpdateByPrimaryKey(BossUserUpdateItemReqDto bossUserUpdateItemReqDto) {
		ResultBase resultBase = new ResultBase();
		BossUser bossUser = new BossUser();
		BeanUtils.copyProperties(bossUserUpdateItemReqDto, bossUser);
		if(StringUtils.isNotBlank(bossUserUpdateItemReqDto.getPassword())) {
			bossUser.setPassword(DigestUtils.sha256Hex(bossUserUpdateItemReqDto.getPassword()));
		} else {
			bossUser.setPassword(null);
		}
		bossUserMapper.updateByPrimaryKeySelective(bossUser);
		resultBase.setSuccess(true);
		resultBase.setMessage("更新成功");
		return resultBase;
	}
	
	/**
	 * 根据主键删除数据
	 * @param keys 被删除对象主键List集合
	 */
	@Transactional
	public ResultBase bossUserDeleteByPrimaryKey(List<Long> keys) {
		ResultBase resultBase = new ResultBase();
		try {
			keys.forEach((key)->{
				bossUserMapper.deleteByPrimaryKey(key);
			});
		} catch (Exception e) {
			resultBase.setMessage(e.getMessage());
			return resultBase;
		}
		resultBase.setSuccess(true);
		resultBase.setMessage("成功删除"+keys.size()+"条记录");
		return resultBase;
	}
	
	/**
	 * 新增数据
	 * @param bossUserAddItemReqDto 新增对象
	 */
	@Transactional
	public ResultBase bossUserSave(BossUserAddItemReqDto bossUserAddItemReqDto) {
		ResultBase resultBase = new ResultBase();
		BossUser bossUser = new BossUser();
		try {
			BeanUtils.copyProperties(bossUserAddItemReqDto, bossUser);
			bossUser.setPassword(DigestUtils.sha256Hex(bossUserAddItemReqDto.getPassword()));
			bossUserMapper.insertSelective(bossUser);
		} catch (Exception e) {
			resultBase.setMessage(e.getCause().getLocalizedMessage());
			return resultBase;
		}
		resultBase.setSuccess(true);
		resultBase.setMessage("新增成功");
		return resultBase;
	}

	/**
	 * 通过用户名查找用户
	 * @param userName 用户名
	 * @return <div style="color:blue;font-size:12px;"></font>
	 */
	public BossUser findByUsername(String userName) {
		BossUserExample example = new BossUserExample();
		example.createCriteria().andUserNameEqualTo(userName);
		List<BossUser> bossUser = bossUserMapper.selectByExample(example);
		if(bossUser.size() > 0) {
			return bossUser.get(0);
		} else {
			return null;
		}
	}
}
